var store = require('store');
var extend = require('object-assign');
var config = require('../config.js');
var bigBonusConfig = config.bigBonus;
var perfectBonusConfig = config.perfectBonus;
var bigBonusCount = bigBonusConfig.count + perfectBonusConfig.count;
var db = model('DB');
var Step = model('Step');
var BigBonus = model('BigBonus');

const bigBonus = 'bigBonus';
const perfectBonus = 'perfectBonus';
const isPrepare = 'isPerfectBonusPrepare';

module.exports = extend(Step(perfectBonus), {

    /* 抽完名单，轮到下一位抽取 */
    nextStep(){
        var step = this.getStep();
        var pickPack = this._getCurrentPickPack();
        if (pickPack.length < step.count) {
            return;
        }

        // 跳到下一轮
        var step = this._getCurrentStepNumber();
        this._setStep(++step);

        // 清除上一轮名单
        this._setCurrentPickPack([]);

        if (step.completed) {
            throw new Error('大奖抽完了');
        }

        console.log(this.getStep().name+' 开始抽奖');
    },

    /* 抽取10名 */
    pick(){
        BigBonus.checkPrepare();
        this.setPrepare(2);
        var step = this.getStep();
        var list = this.getAll();
        var pickPack = list.filter(v=>{return !v.use;})
                            .sort(function(){return Math.random()*0.5;})
                            .slice(0, step.count)
                            .map(v=>{
                                v.use = true;
                                return v;
                            });
        this._setCurrentPickPack(pickPack);
        store.set(bigBonus, list);

        console.log(this.getStep().name+' 抽了'+pickPack.length+'名');

        return pickPack;
    },

    /*十全十美奖名单*/
    getAll(){
        var result = store.get(bigBonus);
        return result;
    },

    add(list){
        var result = this.getAll();
        if (result.length===config.count) {
            throw new Error('十全十美奖名单已经够'+config.count+'名了');
        }
        result = result.concat(list);
        store.set(happyBonus, result);
        this.setPrepare(1);
    },

    setPrepare(status){
        store.set(isPrepare, status);
    },

    getPrepare(){
        return Number(store.get(isPrepare));
    },

});